#include "numpadpanel.h"
#include "windowutil.h"       // 依赖 platform 模块的窗口工具类
#include "configmanager.h"    // 依赖 core 模块的快捷键配置
#include "inputtextedit.h"

#include <QApplication>
#include <QKeyEvent>
#include <QDebug>
#include <QLabel>
#include <QShortcut>

NumpadPanel::NumpadPanel(QWidget *parent)
    : QDialog(parent)
    , m_settings("SmartInput", "Numpad")  // 配置存储：组织名=SmartInput，应用名=Numpad
{
	initUI();
	loadRecentSymbols();	// 最近符号
}

void NumpadPanel::showPanel()
{
	// 居中显示并激活窗口
    WindowUtil::moveToScreenCenter(this);
    show();
    activateWindow();
}

void NumpadPanel::onSymbolButtonClicked(const QString &symbol) {
	// send symbol to focus
	sendSymbolToFocusWidget(symbol);
	addToRecentSymbols(symbol);
	emit symbolSent(symbol);
}

void NumpadPanel::loadRecentSymbols()
{
	// Qsetting 里面去read recnet list default null 
	m_recentSymbols = m_settings.value("RecentSymbols").value<QVector<QString>>();
	// recent symbol btn
	qDeleteAll(m_recentLayout->findChildren<QPushButton*>());
	// 生成最近使用按钮
	for (const QString& symbol : m_recentSymbols) {
		auto* btn = new QPushButton(symbol);
		btn->setFixedSize(40, 30);
		connect(btn,&QPushButton::clicked, this, [this, symbol]() {
			onSymbolButtonClicked(symbol);
		});	
		m_recentLayout->addWidget(btn);
	}
}

void NumpadPanel::addToRecentSymbols(const QString &symbol)
{
	m_recentSymbols.removeAll(symbol);
	m_recentSymbols.prepend(symbol);	// 最新优先 队列
	if (m_recentSymbols.size() > MAX_RECENT_COUNT)	m_recentSymbols.resize(MAX_RECENT_COUNT);

	// async
	m_settings.setValue("RecentSymbols", QVariant::fromValue(m_recentSymbols));
    loadRecentSymbols();
}

void NumpadPanel::initUI()
{
	// 无边框+置顶+固定大小（跨平台适配）
	setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Dialog);
    WindowUtil::adaptPlatformStyle(this);  // 适配系统主题
    setFixedSize(400, 300);                // 固定面板大小
    setStyleSheet(R"(
        NumpadPanel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        QTabWidget::pane {
            border-top: 2px solid #E6E6E6;
        }
        QTabBar::tab {
            width: 80px;
            height: 30px;
            font-size: 12px;
            margin-right: 2px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            background-color: #F5F5F5;
        }
        QTabBar::tab:selected {
            background-color: white;
            border-top: 2px solid #1890FF;
        }
        QPushButton {
            width: 60px;
            height: 40px;
            font-size: 14px;
            border: 1px solid #E6E6E6;
            border-radius: 4px;
            background-color: white;
        }
        QPushButton:hover {
            background-color: #F5F5F5;
        }
        QPushButton:pressed {
            background-color: #E6F7FF;
            border-color: #1890FF;
        }
    )");

	// label + rencentSyb
	QVBoxLayout* mainLayout = new QVBoxLayout(this);
	mainLayout->setContentsMargins(0,0,0,0);
	mainLayout->setSpacing(0);

	// recent syboml
	m_recentWidget = new QWidget();
	m_recentWidget->setFixedHeight(40);
	m_recentLayout = new QHBoxLayout(m_recentWidget);
	m_recentLayout->setContentsMargins(10, 5, 10, 5);
	m_recentLayout->setSpacing(8);
	m_recentLayout->addWidget(new QLabel("最近使用："));
    mainLayout->addWidget(m_recentWidget);

	// 分类 label
	QTabWidget* tabWidget = new QTabWidget();
	initSymbolTabs(tabWidget);
	mainLayout->addWidget(tabWidget);

	// get shutcut ctrl + alt + n 快捷键：从配置读取（需求2.4.1）
    ConfigManager *config = ConfigManager::getInstance();
    QString shortcut = config->getShortcutConfig().showNumpad;
    QShortcut *showShortcut = new QShortcut(QKeySequence(shortcut), this);
    connect(showShortcut, &QShortcut::activated, this, &NumpadPanel::showPanel);

    // 监听快捷键配置变更
    connect(config, &ConfigManager::shortcutConfigChanged, this, [this](const ShortcutConfig::Data& config) {
        m_showShortcut->setKey(QKeySequence(config.showNumpad));
    });
}

void NumpadPanel::initSymbolTabs(QTabWidget *tabWidget)
{
	// 常用分页 syboml
	QWidget* commonTab = new QWidget();
	QGridLayout* commonLayout = new QGridLayout(commonTab);
	commonLayout->setContentsMargins(20, 10, 20, 10);
	commonLayout->setSpacing(10);
	QStringList commonSymbols = {
		"!", "@", "#", "￥", "%", "^",
        "&", "*", "(", ")", "_", "+",
        "[", "]", "{", "}", "|", "\\",
        ";", "'", ":", "\"", ",", "."
	};
	addSymbolButtons(commonLayout, commonSymbols);
	tabWidget->addTab(commonTab, "常用");

	// nums symbols
	QWidget* mathTab = new QWidget();
    QGridLayout* mathLayout = new QGridLayout(mathTab);
    mathLayout->setContentsMargins(20, 10, 20, 10);
    mathLayout->setSpacing(10);
    QStringList mathSymbols = {
        "≈", "≠", "≤", "≥", "+", "-",
        "×", "÷", "±", "√", "∛", "∑",
        "∫", "∂", "∆", "π", "θ", "∞",
        "∈", "∉", "⊂", "⊃", "∩", "∪"
    };
    addSymbolButtons(mathLayout, mathSymbols);
    tabWidget->addTab(mathTab, "数学");

	// 单位 symbols
	QWidget* unitTab = new QWidget();
    QGridLayout* unitLayout = new QGridLayout(unitTab);
    unitLayout->setContentsMargins(20, 10, 20, 10);
    unitLayout->setSpacing(10);
    QStringList unitSymbols = {
        "cm", "mm", "m", "km", "g", "kg",
        "mg", "t", "s", "min", "h", "d",
        "℃", "℉", "°", "%", "‰", "ppm",
        "$", "€", "￥", "￡", "¥", "₤"
    };
    addSymbolButtons(unitLayout, unitSymbols);
    tabWidget->addTab(unitTab, "单位");
}

void NumpadPanel::addSymbolButtons(QGridLayout *layout, const QStringList &symbols)
{
	// 6cols 按钮
	for (int i = 0; i < symbols.size(); i++) {
		QString symbol = symbols[i];
		QPushButton* btn = new QPushButton(symbol);
		connect(btn, &QPushButton::clicked, this, [this, symbol]() {
			onSymbolButtonClicked(symbol);
		});

		// foreach fill layout
		int row = i / 6;
		int col = i % 6;
		layout->addWidget(btn, row, col);
	}
}

void NumpadPanel::sendSymbolToFocusWidget(const QString &symbol)
{
	// 获取focus
	InputTextEdit *input = InputTextEdit::getInstance();
    if (input && input->hasFocus()) {
        input->insertPlainText(symbol);
        return;
    }

    // 兼容其他焦点控件
    QWidget *focusWidget = QApplication::focusWidget();
    if (focusWidget) {
        QKeyEvent pressEvent(QEvent::KeyPress, Qt::Key_unknown, Qt::NoModifier, symbol);
        QApplication::sendEvent(focusWidget, &pressEvent);
    }

	// 发送symbol keybord event
	QKeyEvent pressEvent(QEvent::KeyPress, 0, Qt::NoModifier, symbol);
	QKeyEvent releaseEvent(QEvent::KeyRelease, 0, Qt::NoModifier, symbol);
    QApplication::sendEvent(focusWidget, &pressEvent);
    QApplication::sendEvent(focusWidget, &releaseEvent);
}
